<template>
  <NDrawer :show="visible" :width="600" title="资产详情" @update:show="emit('update:visible', $event)">
    <NDrawerContent>
      <NSpin :show="loading">
        <NDescriptions v-if="assetData" :column="1" label-placement="left" bordered>
          <NDescriptionsItem label="资产名称">
            {{ assetData.name }}
          </NDescriptionsItem>
          <NDescriptionsItem label="资产类型">
            <NTag :type="getAssetTypeTag(assetData.assetType).type">
              {{ getAssetTypeTag(assetData.assetType).label }}
            </NTag>
          </NDescriptionsItem>
          <NDescriptionsItem label="所属分类">
            {{ assetData.categoryName || '-' }}
          </NDescriptionsItem>
          <NDescriptionsItem label="分级标识">
            <NTag v-if="assetData.level" :type="getAssetLevelTag(assetData.level).type">
              {{ getAssetLevelTag(assetData.level).label }}
            </NTag>
            <span v-else>-</span>
          </NDescriptionsItem>
          <NDescriptionsItem label="状态">
            <NTag :type="getAssetStatusTag(assetData.status || 'DRAFT').type">
              {{ getAssetStatusTag(assetData.status || 'DRAFT').label }}
            </NTag>
          </NDescriptionsItem>
          <NDescriptionsItem label="来源类型">
            {{ assetData.sourceType || '-' }}
          </NDescriptionsItem>
          <NDescriptionsItem label="来源ID">
            {{ assetData.sourceId || '-' }}
          </NDescriptionsItem>
          <NDescriptionsItem label="标签">
            <NSpace v-if="assetData.tags">
              <NTag v-for="tag in parseTags(assetData.tags)" :key="tag" type="info">
                {{ tag }}
              </NTag>
            </NSpace>
            <span v-else>-</span>
          </NDescriptionsItem>
          <NDescriptionsItem label="使用次数">
            {{ assetData.useCount || 0 }}
          </NDescriptionsItem>
          <NDescriptionsItem label="最后使用时间">
            {{ assetData.lastUseTime || '-' }}
          </NDescriptionsItem>
          <NDescriptionsItem label="描述">
            {{ assetData.description || '-' }}
          </NDescriptionsItem>
          <NDescriptionsItem label="元数据">
            <NCode v-if="assetData.metadata" :code="formatJson(assetData.metadata)" language="json" />
            <span v-else>-</span>
          </NDescriptionsItem>
          <NDescriptionsItem label="备注">
            {{ assetData.remark || '-' }}
          </NDescriptionsItem>
          <NDescriptionsItem label="创建时间">
            {{ assetData.createTime }}
          </NDescriptionsItem>
          <NDescriptionsItem label="更新时间">
            {{ assetData.updateTime }}
          </NDescriptionsItem>
        </NDescriptions>
      </NSpin>
    </NDrawerContent>
  </NDrawer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import type { DataAsset } from '@/service/api/dataplatform/asset';
import { getDataAsset, incrementUseCount } from '@/service/api/dataplatform/asset';
import { useLoading } from '@sa/hooks';

interface Props {
  visible: boolean;
  assetId: number;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  'update:visible': [visible: boolean];
}>();

const { loading, startLoading, endLoading } = useLoading(false);
const assetData = ref<DataAsset | null>(null);

watch(
  () => props.visible,
  async val => {
    if (val && props.assetId) {
      await loadAssetDetail();
      // 增加使用次数
      try {
        await incrementUseCount(props.assetId);
      } catch (error) {
        // 忽略错误
      }
    }
  }
);

async function loadAssetDetail() {
  startLoading();
  try {
    const { data } = await getDataAsset(props.assetId);
    assetData.value = data;
  } catch (error) {
    window.$message?.error('加载资产详情失败');
  } finally {
    endLoading();
  }
}

function getAssetTypeTag(type: string) {
  const typeMap: Record<string, { label: string; type: any }> = {
    TABLE: { label: '数据表', type: 'info' },
    VIEW: { label: '视图', type: 'success' },
    API: { label: 'API', type: 'warning' },
    REPORT: { label: '报表', type: 'error' }
  };
  return typeMap[type] || { label: type, type: 'default' };
}

function getAssetLevelTag(level: string) {
  const levelMap: Record<string, { label: string; type: any }> = {
    PUBLIC: { label: '公开', type: 'success' },
    INTERNAL: { label: '内部', type: 'info' },
    CONFIDENTIAL: { label: '机密', type: 'warning' },
    SECRET: { label: '绝密', type: 'error' }
  };
  return levelMap[level] || { label: level, type: 'default' };
}

function getAssetStatusTag(status: string) {
  const statusMap: Record<string, { label: string; type: any }> = {
    DRAFT: { label: '草稿', type: 'default' },
    PUBLISHED: { label: '已发布', type: 'success' },
    ARCHIVED: { label: '已归档', type: 'warning' },
    DESTROYED: { label: '已销毁', type: 'error' }
  };
  return statusMap[status] || { label: status, type: 'default' };
}

function parseTags(tags: string): string[] {
  try {
    return JSON.parse(tags);
  } catch {
    return tags.split(',').filter(t => t.trim());
  }
}

function formatJson(json: string): string {
  try {
    return JSON.stringify(JSON.parse(json), null, 2);
  } catch {
    return json;
  }
}
</script>
